<template>
    <div>
        <div class="search">
            <input class="search-input" v-model="search" type="text" placeholder="请输入城市名或拼音">
        </div>
        <div class="list" v-show="search" ref="search-list">
            <ul>
                <li class="item border-bottom" v-for="item in list" :key="item.id" @click="handleCityClick(item.name)">
                    {{ item.name }}
                </li>
            </ul>
        </div>
    </div>
</template>

<script>
import BScroll from 'better-scroll'
import { mapMutations } from 'vuex'

export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      search: '',
      list: [],
      timer: null
    }
  },
  methods: {
    ...mapMutations(['changeCity']),
    handleCityClick (city) {
      // this.$store.commit('changeCity', city)
      this.changeCity(city)
      this.$router.push('/')
    }
  },
  watch: {
    search () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.list = []
        for (var key in this.cities) {
          this.cities[key].forEach((item) => {
            if (item.spell.indexOf(this.search) > -1 || item.name.indexOf(this.search) > -1) {
              this.list.push(item)
            }
          })
        }
        if (!this.list.length) {
          this.list.push({
            name: '没有找到匹配数据',
            id: 1
          })
          console.log(this.list)
        }
      }, 16)
    }
  },
  mounted () {
    const element = this.$refs['search-list']
    this.scroll = new BScroll(element)
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/variables.styl'
.search
    height .72rem
    padding 0 .1rem
    background $bgColor
    .search-input
        box-sizing border-box
        width 100%
        height .62rem
        line-height .62rem
        padding 0 .1rem
        text-align center
        border-radius .06rem
        color #666
.list
    overflow hidden
    position absolute
    top 1.58rem
    left 0
    right 0
    bottom 0
    z-index 1
    background-color #eee
    .item
        padding-left .2rem
        line-height .54rem
        background-color #fff
</style>
